package sql.ddl.coluna;

import java.util.ArrayList;

import sql.ddl.Tabela;
import sql.ddl.TokensSQL;

public class ForeignKey implements TokensSQL {
	ArrayList<Coluna[]> colunas = null;

	String constraint = null;

	Tabela outra = null;

	public ForeignKey(Tabela referencia, ArrayList<Coluna[]> colunas) {
		this.outra = referencia;
		this.colunas = colunas;
	}

	public ForeignKey(Tabela tabela, Coluna[] colunasKey) throws Exception {
		this.outra = tabela;
		this.colunas = new ArrayList<Coluna[]>();
		int i = 0;
		for (Coluna coluna2 : colunasKey) {
			this.colunas.add(new Coluna[] { coluna2,
					outra.getPrimaryKey().getColunas().get(i++) });
		}

	}

	public String codigoSQL() {
		return constraint() + FOREIGN + SPACE + KEY + BEGINPARENTES + campos(0)
				+ ENDPARENTES + REFERENCES + SPACE + outra.getALLName()
				+ BEGINPARENTES + campos(1) + ENDPARENTES;
	}

	private String constraint() {
		return constraint != null ? CONSTRAINT + SPACE + constraint + SPACE
				: NONVALUE;
	}

	private String campos(int j) {
		String s = colunas.get(0)[j].getNome();
		for (int i = 1; i < colunas.size(); i++) {
			s += VIRGUL + colunas.get(i)[j].getNome();
		}
		return s;
	}

	public void setConstraint(String alias) {
		this.constraint = alias;
	}

	public String getNome() {
		return constraint;
	}

	public void setDefaultConstraint() {
		constraint = outra.getNome().toUpperCase();
		for (Coluna[] c : colunas)
			constraint += "_" + c[0].getNome().toUpperCase();
	}
}
